package com.cos.hospital.ui.login;

import android.content.Intent;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.helper.KTextWatcher;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.bean.user.CodeBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.URegular;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.widget.ProgressDialog;
import com.cos.hospital.widget.TimeButton;
import com.google.gson.JsonObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * @Description: 重置密码.1
 * @Author: Kosmos
 * @Date: 2018年9月10日 17:01
 * @Email: KosmoSakura@foxmail.com
 */
public class PasswordResetAcitivity extends BaseActivity {
    @BindView(R.id.reset_phone)
    EditText edtPhone;
    @BindView(R.id.reset_verification_code)
    EditText edtCode;
    @BindView(R.id.reset_verification_code_get)
    TimeButton codeTime;
    @BindView(R.id.reset_done)
    TextView tDone;
    private String canNext;
    private String phone;
    private Map<String, String> codeMap;

    @Override
    protected int layout() {
        return R.layout.activity_password_reset;
    }

    @Override
    protected void init() {
        setTitleLeftIcon();
        setTitleCenterTxt(getString(R.string.forget_password));
        canNext = "";
        codeMap = new HashMap<>();
        checkCodebtn();
        checkDonebtn();
    }

    @Override
    protected void logic() {
        /*
         * 1.注册手机号栏失去焦点时验证录入内容是否符合手机号码规则，不符合手机号码规则，提示“请输入正确的手机号码！”；
         * 验证该手机号码后台是否存在，若不存在，则提示“该号码未注册，请联系管理人员！”；
         * 手机号码验证不通过，不能点击获取验证码，并且不能点击立即验证按钮；
         *
         * 2.短信验证码栏失去焦点时验证录入内容是否符合规则，格式为6位数字，
         * 不符合则提示“验证码为6位数字”，并且不能点击立即验证按钮；
         *
         *3.点击“立即验证”验证短信验证码，不正确则提示“短信验证码错误”，
         * 短信验证码栏重新获取到输入焦点；正确则进入修改密码页面；
         * */
        edtPhone.addTextChangedListener(new KTextWatcher() {
            @Override
            public void afterTextChanged(Editable txtEnd) {
                checkCodebtn();
                checkDonebtn();
            }
        });
        edtCode.addTextChangedListener(new KTextWatcher() {
            @Override
            public void afterTextChanged(Editable txtEnd) {
                checkDonebtn();
            }
        });
        edtPhone.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!UTxt.isEmpty(edtPhone) && !URegular.checkPhoneNum(edtPhone.getText().toString())) {
                    showNotice(getString(R.string.phone_number_error));
                }
            }
        });
        edtCode.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!UTxt.isEmpty(edtCode) && edtCode.length() != 6) {
                    showNotice(getString(R.string.verification_code_about));
                }
            }
        });
    }

    @OnClick({R.id.title_back, R.id.reset_done, R.id.reset_verification_code_get})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.reset_done:
                checkDonebtn();
                if (UTxt.isEmpty(canNext)) {
                    Intent intent = new Intent(this, PasswordChangeActivity.class);
                    intent.putExtra(Code.SP.PHONE, phone);
                    startActivity(intent);
                    finish();
                } else {
                    showNotice(canNext);
                }
                break;
            case R.id.reset_verification_code_get://获取验证码
                if (codeTime.isRunning()) {
                    USnackbar.showWarning(context, "请" + codeTime.getTime() + "秒后再试");
                    return;
                }
                checkCodebtn();
                if (UTxt.isEmpty(codeTime.getState())) {
                    getVerificationCode();
                } else {
                    showNotice(codeTime.getState());
                }
                break;
        }
    }

    private void getVerificationCode() {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("mobile", phone);
        UHttp.start(getServes().getVerificationCode(jsonObject), "发送手机验证码", new HttpMsgListener<ResultBean<CodeBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<CodeBean> dto) {
                if (dto.isSuccess()) {
                    CodeBean codeBean = dto.getResult();
                    if (codeBean != null) {
                        String code = codeBean.getCode();
                        codeMap.put(phone, code);
                        codeTime.run(60);
                        showNotice(getString(R.string.verification_code_sended));
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void checkDonebtn() {
        String newPhone = edtPhone.getText().toString();
        String code = edtCode.getText().toString();
        if (UTxt.isEmpty(edtPhone)) {
            canNext = getString(R.string.phone_number_enter);
        } else if (UTxt.isEmpty(edtCode)) {
            canNext = getString(R.string.verification_code_enter);
        } else if (!URegular.checkPhoneNum(newPhone)) {
            canNext = getString(R.string.phone_number_error);
        } else if (edtCode.length() != 6 || !URegular.checkNumber(code)) {
            canNext = getString(R.string.verification_code_about);
        } else if (!code.equals(codeMap.get(newPhone))) {
            canNext = getString(R.string.verification_code_error);
        } else {
            canNext = "";
        }
        if (UTxt.isEmpty(canNext)) {
            tDone.setBackgroundResource(R.drawable.rect_green);
        } else {
            tDone.setBackgroundResource(R.drawable.rect_gray_light);
        }
    }

    private void checkCodebtn() {
        phone = edtPhone.getText().toString();
        if (UTxt.isEmpty(edtPhone)) {
            codeTime.setState(getString(R.string.phone_number_enter));
        } else if (!URegular.checkPhoneNum(phone)) {
            codeTime.setState(getString(R.string.phone_number_error));
        } else {
            codeTime.setState("");
        }
    }
}
